#!/usr/bin/env bash
set -e

root_dir=$(git rev-parse --show-toplevel)

this_dir=${BASH_SOURCE[0]%/*}
. "${this_dir}"/lib/eslintignore.sh


## CLI PARSING

usage() {
    cat >&2 <<EOF
usage: tools/fmt [--all]

Options:
  --all       Run on all files (default: only files changed in this
              branch, as found by \`tools/git changed-files\`.)
EOF
    exit 2
}

all=
while (( $# )); do
    case "$1" in
        --all) all=1; shift;;
        *) usage;;
    esac
done


## EXECUTION

cd "$(git rev-parse --show-toplevel)"

PATH=node_modules/.bin:"$PATH"

if [ -z "$all" ]; then
    candidates=( $(tools/git changed-files "$(tools/git base)" -- 'src/*.js') )
else
    candidates=( 'src/**/*.js' )
fi
files=( $(apply_eslintignore "${candidates[@]}" ) )

prettier-eslint \
    --write \
    --eslint-config-path "${root_dir}"/tools/formatting.eslintrc.yaml \
    --log-level=warn \
    "${files[@]}"
eslint --no-eslintrc -c tools/formatting.eslintrc.yaml --fix "${files[@]}"
